package com.lvmama.common.utils;

import java.io.BufferedWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

import org.apache.poi.ss.formula.functions.T;

import com.lvmama.common.constants.FieldTypeAnnotation;

@Slf4j
public class ExportCSVUtils {
	
   /**
    * 导出csv
    * @param dataList 数据列表
    * @param bf 文件流
    * @param pattern 时间格式
    * @throws Exception
    */
    @SuppressWarnings("hiding")
	public static <T> void exportCSV(List<T> dataList, BufferedWriter bf, String pattern) throws Exception{
    	if (dataList == null || dataList.size() == 0){
    		return;
    	}
        int i = 0;
    	for (Iterator<T> iterator = dataList.iterator(); iterator.hasNext();) {
    		StringBuffer textValue = new StringBuffer();
    		StringBuffer headers = new StringBuffer();
    		T t = (T)iterator.next();
    		@SuppressWarnings("unchecked")
			Class<T> clz = (Class<T>) t.getClass();  
    		Field[] fields = clz.getDeclaredFields(); 
    		
	    	for(Field field : fields){
	    		//通过实体属性注解获取标题
	    		boolean fieldHasAnno = field.isAnnotationPresent(FieldTypeAnnotation.class);  
	    		if(fieldHasAnno){ 
	    			FieldTypeAnnotation fieldAnno = field.getAnnotation(FieldTypeAnnotation.class);
	    			if (i == 0){
	    				headers.append(fieldAnno.fieldName() + ",");
	    			}
	    			String fieldName = field.getName();
	    			try {
	    				//根据属性名称获取get方法
	    				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
		    			Method getMethod = clz.getMethod(getMethodName, new Class[] {});
		    			Object value = getMethod.invoke(t, new Object[] {});
		    			if (value == null){
		    				textValue.append(" ,") ;
		    				continue;
		    			}
	                    if (value instanceof Date) {
	                        Date date = (Date) value;
	                        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
	                        textValue.append(sdf.format(date) + ",");
	                    }
	                    else {
	                        // 其它数据类型都当作字符串简单处理
	                        textValue.append(value.toString().replaceAll(",","") + ",");
	                    }
					} catch (Exception e) {
						log.error(e.getMessage());
					}
	    			
	    		}
	        }
	    	i++;
    		if (headers != null){
    			bf.write(headers.toString());
    			bf.newLine();
    		}
    		if (textValue != null && textValue.length() > 0){
    			bf.write(textValue.toString());
    		}
		}

    }
}
